package com.mewp.permissions.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 生成JWT令牌的工具类
 *
 * @author mewp
 * @version 1.0
 * @date 2023/7/30 14:41
 */
public class JwtHelper {
    /**
     * 过期时间 24 * 60 * 60 * 1000（1天）
     */
    private static final long TOKEN_EXPIRATION = 24 * 60 * 60 * 1000L;
    /**
     * 明文密钥
     */
    private static final String TOKEN_SIGN_KEY = "yZ7yM4jO0qX6gX7s";

    /**
     * 生成token
     *
     * @param userId   用户Id
     * @param userName 用户名
     * @return token字符串
     */
    public static String createToken(Long userId, String userName) {
        return Jwts.builder()
                .setSubject("auth-user")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .claim("userId", userId)
                .claim("username", userName)
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 根据token获取用户id
     *
     * @param token token字符串
     * @return userId
     */
    public static Long getUserId(String token) {
        try {
            if (!StringUtils.hasText(token)) {
                return null;
            }
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(TOKEN_SIGN_KEY)
                    .parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据token获取用户名
     *
     * @param token token字符串
     * @return username
     */
    public static String getUserName(String token) {
        try {
            if (!StringUtils.hasText(token)) {
                return null;
            }
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(TOKEN_SIGN_KEY)
                    .parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "admin");
        System.out.println(token);

        System.out.println("userId = " + JwtHelper.getUserId(token));
        System.out.println("username = " + JwtHelper.getUserName(token));
    }
}
